package net.java.mediasystems.web.bean;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;

import net.java.mediasystems.database.core.model.MediaType;
import net.java.mediasystems.database.core.service.FindableWithNameAndMediaType;
import net.java.mediasystems.web.WebUtil;

import org.primefaces.util.ComponentUtils;

public abstract class AbstractAddObjectWithNameAndMediaTypeBean implements Serializable {

	private static final long serialVersionUID = -5876270539314243024L;

	String name;
	MediaType type;
	List<MediaType> availableMediaTypes;
	
	abstract FindableWithNameAndMediaType<?> getFindableWithNameAndMediaType();
	
	/**
	 * Validation-Method to check, if the Name already exists for the selected MediaType.
	 * 
	 * @param facesContext FacesContext
	 * @param uiComponent UIComponent
	 * @param value Object
	 */
	public void checkNameForMediaType(FacesContext facesContext, UIComponent uiComponent, Object value) {
		String name = (String) value; 
		
		UIInput uiInput = (UIInput) ComponentUtils.findComponent(FacesContext.getCurrentInstance().getViewRoot(), "typeSelect");
		MediaType mediaType = MediaType.valueOf((String) uiInput.getSubmittedValue());
		
		if (getFindableWithNameAndMediaType().getByMediaTypeAndName(mediaType, name) != null) {
			throw new ValidatorException(WebUtil.createErrorMessageLocalized("inc_nameandtypeinput_error_namealreadyexists"));
		}
	}
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public MediaType getType() {
		return type;
	}
	
	public void setType(MediaType type) {
		this.type = type;
	}
	
	public List<MediaType> getAvailableMediaTypes() {
		if (this.availableMediaTypes == null) {
			this.availableMediaTypes = new ArrayList<MediaType>(Arrays.asList(MediaType.values()));
		}
		return availableMediaTypes;
	}
	
	public void setAvailableMediaTypes(List<MediaType> availableMediaTypes) {
		this.availableMediaTypes = availableMediaTypes;
	}
}
